<?php
namespace app\controllers\crontab;
use GuzzleHttp\Client;

use yii;
class EsTestController extends \app\base\Controller
{
    /**
     * 字段转换问题
     */
    private $fieldToEs = 
       ['user_id'=>'userId','site_user_id'=>'siteUserId','email'=>'email','email_domain'=>'emailDomain',
           'email_type'=>'emailType','firstname'=>'firstname','lastname'=>'lastname','birthday'=>'birthday',
           'region_code'=>'regionCode','reg_time'=>'regTime','reg_source'=>'regSource','last_login'=>'lastLogin',
           'last_order_time'=>'lastOrderTime','is_received_promo'=>'isReceivedPromo','subscibe_frequency'=>'subscibeFrequency',
           'sub_source'=>'subSource','unsub_time'=>'unsubTime','unsub_source'=>'unsubSource','is_block'=>'isBlock',
           'user_flag'=>'userFlag','is_del'=>'isDel','risk_status'=>'riskStatus','is_test'=>'isTest','is_bound'=>'isBound',
           'is_complaint'=>'isComplaint','last_open'=>'lastOpen','lang'=>'lang','last_sent_time'=>'lastSentTime',
           'last_click_time'=>'lastClickTime','login_device_type'=>'loginDeviceType','sex'=>'sex','is_received_custom_promo'=>'isReceivedCustomPromo',
           'queue_id'=>'queueIds','site_user_id'=>'siteUserId','site_user_id'=>'siteUserId','low_category_id'=>'behaviors.catId',
           'user_behavior'=>'behaviors.behavior','5days_count'=>'login5daysCount','10days_count'=>'login10daysCount',
           '15days_count'=>'login15daysCount','20days_count'=>'login20daysCount','30days_count'=>'login30daysCount',
           'user_id'=>'userId','update_day'=>'loginUpdateDay','5days_count'=>'open5daysCount',
           '10days_count'=>'open10daysCount','15days_count'=>'open15daysCount','20days_count'=>'open20daysCount',
           '30days_count'=>'open30daysCount','60days_count'=>'open60daysCount','90days_count'=>'open90daysCount',
           '180days_count'=>'open180daysCount','user_id'=>'userId','update_day'=>'openUpdateDay','5days_count'=>'click5daysCount',
           '10days_count'=>'click10daysCount','15days_count'=>'click15daysCount','20days_count'=>'click20daysCount',
           '30days_count'=>'click30daysCount','60days_count'=>'click60daysCount','90days_count'=>'click90daysCount',
           '180days_count'=>'click180daysCount','user_id'=>'userId','update_day'=>'clickUpdateDay','5days_count'=>'order5daysCount',
           '10days_count'=>'order10daysCount','15days_count'=>'order15daysCount','20days_count'=>'order20daysCount',
           '30days_count'=>'order30daysCount','60days_count'=>'order60daysCount','90days_count'=>'order90daysCount','180days_count'=>'order180daysCount',
           'user_id'=>'userId','update_day'=>'orderUpdateDay','send_email_count'=>'sendEmailCount','login_count'=>'loginCount',
           'open_email_count'=>'openEmailCount','click_email_count'=>'clickEmailCount','order_count'=>'orderCount'];
    
    /**
     * 自定义分群数据刷成适合es版
     */
   // public function actionSysGroupAdd
    /**
     * 分群数据添加适合es版
     */
    public function actionSysGroupAddEs()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        if (empty($formData['site_id'])) {
            echo '没有指定网站';
            exit;
        } else {
           $siteId = $formData['site_id'];
        }
        $selectSql = " select other_con,user_group_id from user_group where site_id = {$siteId} and user_group_type != 1 ";
       
        $userGroupInfo = yii::$app->db->createCommand($selectSql)->queryAll();
        foreach ($userGroupInfo as $userGroupInfoVal) {
            $conditionCon = $userGroupInfoVal['other_con'];
            if (!empty($conditionCon)) {
                $conditionConArr = \GuzzleHttp\json_decode($conditionCon,true);
                $esFilterArr = [];
                $esFilterArr['filters'] = [];
               
                foreach ($conditionConArr as $conditionConArrKey=>$conditionConArrVal) {
                    $esFilterArrTemp = [];
                    $esFilterArrTemp["field"] = $this->fieldToEs[$conditionConArrKey];
                    if (is_numeric($conditionConArrVal)) {
                        $conditionConArrVal = intval($conditionConArrVal);
                    }
                    $esFilterArrTemp["values"] = [$conditionConArrVal];
                    $esFilterArr['filters'][] = $esFilterArrTemp;
                }
                $esFilterArrStr = json_encode($esFilterArr);
                $param = [];
                $param[":es_filters"] = $esFilterArrStr;
                $updateSql = " update user_group set es_filters = :es_filters where user_group_id = {$userGroupInfoVal['user_group_id']}";
                Yii::$app->db->createCommand($updateSql)->bindValues($param)->execute();
            }
        }
    }
    public function actionTest()
    {
//        
//        $startStructureArr = [
//            'data'=>
//            [
//                [
//                'data'=>['A','B','C'],
//                ],
//                [
//                'data'=>['D','E'],
//                ],
//            ],
//            'isMany'=>true,
//            'operation' => 'and',
//        ];
           
          // 两层或与式转与或式
          $startStructureArr = [ // 定义逻辑运算的数据 (A+B+C)(E+F) 转成与或式
            ['A','B','C'],['E','F'],['G','H']
          ];
          
//           $startStructureArr = [ // 定义逻辑运算的数据 (A+B+C)(E+F) 转成与或式
//            'Aa','Tt',['Bb','Cc']
//          ];
           
//           $startStructureArr = [['Bb','Cc']];
//           
//           $startStructureArr = [['Bb','Cc']];
////           echo '<pre>';
//           var_dump($startStructureArr);
//           exit;
          $changeStructureArr = Yii::$app->logicoperation->simplificationOperation($startStructureArr);
          echo '<pre>';
          var_dump($changeStructureArr);
          
          echo '<br>----------------------------------------<br>';
          // 多层或与式转与或式
          $sys1 = [['abc'],['e','f']];
          $changeSys1 = Yii::$app->logicoperation->simplificationOperation($sys1);
          var_dump($changeSys1);
          exit;
          $sys2 = 'hij';
          $sys3 = 'LN';
          $changeSys = $changeSys1;
                  
          $changeSys[] = $sys2;
          $changeSys[] = $sys3;
         
          $hebing =Yii::$app->logicoperation->simplificationOperation([$changeSys,['MN','VP']]);
          echo '<br>-----------------------------------------------<br>';
          var_dump($hebing);
          exit;
          $startStructureArr = [ // 定义逻辑运算的数据
            ['A','B','C'],['E','F'],['G','H']
          ];
         // $relationshipArr = ['+','*'];

         
//         $startStructureArr = [
//            'data'=>
//            [
//                [
//                'data'=>['A','B','C'],
//                'operation'=>'or',
//                ],
//                [
//                'data'=>['D','E','F'],
//                'operation'=>'or',
//                ],
//            ],
//            'isMany'=>true,
//            'operation' => 'and',
//        ];
       // Yii::$app->logicoperation->simplification($startStructureArr);

        exit;
        // $searchData = [["field"=>"userId","values"=>[4624374]]];
        $searchData = [["field"=>"regSource","values"=>["GBUS"]]];
        $response = yii::$app->es->search($searchData);
        echo "<pre>";
        var_dump($response);
        exit;
       $url = "http://10.60.35.93:8081/emp/search";
       $client = new Client(['timeout' => 30]);
       $jsonData = '{
	"domain": "emp_gearbest",
	"accessToken": "15bda4c014524ef1bef205c82f6bd7bf",
	"pageNo": 1,
	"pageSize": 16,
	"agent": "web",
	"resource": "user",
	"version": 3,
	"filters": [{
		"field": "userId",
		"values": [
			4624374
		]
	}]
}';
       
//       $response = $client->request('POST',$url, ['json' => $jsonData]);
//        echo '<pre>';
//        var_dump($response);
//        exit;
//        $responseJsonString = $response->getBody()->getContents();
//            $returnData = \GuzzleHttp\json_decode($responseJsonString,true);
//            
//            $returnBody = json_decode($returnData['body'],true);
//            echo "<pre>";
//            var_dump($returnData);
//            exit;
//        
       $this->handleRequest($url, $jsonData);
    }
    
    public function handleRequest($url, $jsonData, $jsonSerial=true)
    {
        try {
            $result = array();
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            // 超时设定
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_URL, $url);
            $headers = array(
                'User-Agent: EDM Search Client',
            );
            if ($jsonSerial) {
                // body raw
                $headers[] = 'Content-Type: application/json';
            }
            if (php_sapi_name() !== 'cli') {
                if (isset($_SERVER['HTTP_REFERER'])) {
                    $headers[] = 'Referer:' . $_SERVER['HTTP_REFERER'];
                } else if (isset($_SERVER['HTTP_HOST'])) {
                    $headers[] = 'Referer:' . $_SERVER['HTTP_HOST'];
                }
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);

           
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

            // 执行请求
            $resp = curl_exec($ch);
            // 记录提交信息
            $info = curl_getinfo($ch);

            $message = " Response Info " . json_encode($info);
            $curl_error_code = curl_errno($ch);
            if ($curl_error_code) {
                $message .= " Curl Error Code: " . $curl_error_code . " - " . curl_error($ch);
                if ($curl_error_code == CURLE_OPERATION_TIMEOUTED) {
                    $result = array('succeed' => false, 'code' => '0000', 'msg' => '连接超时，请稍后重试');
                } else {
                    $result = array('succeed' => false, 'code' => str_pad($curl_error_code, 4, '0'), 'msg' => curl_error($ch));
                }
            } else {
                if (isset($info['http_code']) && $info['http_code'] == 200) {
                    if ($jsonSerial) {
                        $result = json_decode($resp, true);
                    } else {
                        $result = $resp;
                    }
                } else {
                    // 502 之类
                    $result['succeed'] = false;
                    if (!$info['http_code']) {
                        $result['code'] = '0000';
                        $result['msg'] = '连接超时，请稍后重试';
                    } else {
                        $result['code'] = 'http_code';
                        $result['msg'] = $info['http_code'];
                    }
                }
            }
           // $this->writeLog($message);
            // 关闭请求
            curl_close($ch);
            echo '<pre>';
            var_dump($result);
            exit;
            return $result;
        } catch (\Exception $e) {
            echo 'hhhhhhhhhh';
            //$this->writeLog($e->getTraceAsString(), true);
            var_dump($e->getMessage());
            exit;
            return array('succeed' => false, 'code' => '0000', 'msg' => $e->getTraceAsString());
        }
    }
    
    public function actionCurlTest()
    {
        $url = "http://10.60.35.93:8081/emp/search";
         $jsonData = '{
	"domain": "emp_gearbest",
	"accessToken": "15bda4c014524ef1bef205c82f6bd7bf",
	"pageNo": 1,
	"pageSize": 16,
	"agent": "web",
	"resource": "user",
	"version": 3,
	"filters": [{
		"field": "userId",
		"values": [
			4624374
		]
	}]
}';
        $ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$jsonData);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,60);
curl_setopt($ch,CURLOPT_TIMEOUT,60);

$return = curl_exec($ch);
echo '<pre>';
echo 'hhhhhhhhh<br>';
var_dump($return);
exit;
            $item['url'] = $url;
           // $item['options'][CURLOPT_COOKIE] = $cookie;
            $item['options'][CURLOPT_NOSIGNAL] = 1;         // 不使用信号，让worker可以小于1s启动
            $item['options'][CURLOPT_TIMEOUT_MS] = 100;      // 给足够的时间worker启动
            $item['options'][CURLOPT_POSTFIELDS] = $jsonData;
            $response = yii::$app->curl->execute($item);
           echo '<pre>';
           var_dump($response);
           exit;
         
    }
}